import time
from flask import request

from settings import Setting
from util.JwtUtil import create_jwt_token, check_jwt_token, decode_jwt_token


def get_login_info():
    token = ''
    login_info = {}
    secret = Setting.secret
    if 'token' in request.cookies:
        token = request.cookies['token']
    if check_jwt_token(token, secret):
        login_info = decode_jwt_token(token, secret)
    return login_info


def set_login_info(res, user, max_age=60 * 60 * 24 * 5):
    secret = Setting.secret
    login_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    login_info = {'user': user, 'login_time': login_time, 'max_age': max_age}
    token_str = create_jwt_token(login_info, secret)
    res.set_cookie('token', token_str, max_age)


def set_login_out(res):
    res.set_cookie('token', '', 0)


def valid_login(login_info):
    current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    current_time = time.mktime(time.strptime(current_time, '%Y-%m-%d %H:%M:%S'))
    login_time = login_info['login_time']
    time.strptime(login_time, "%Y-%m-%d %H:%M:%S")
    login_time = time.mktime(time.strptime(login_time, '%Y-%m-%d %H:%M:%S'))
    max_age = login_info['max_age']
    if login_time <= current_time <= (login_time + max_age):
        return True
    return False
